<template>
  <q-page class="analysis-container q-pa-md">
    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="text-h5 text-weight-bold q-mb-md text-primary">
        <q-icon name="warning" size="sm" class="q-mr-sm"/>
        告警业务分析
      </div>
      <q-card flat bordered class="search-card">
        <q-card-section>
          <q-form @submit.prevent="addQueryAndSearch" class="search-form">
            <q-select
              v-model="queryInput"
              :options="filteredOptions"
              label="输入告警内容"
              use-input
              fill-input
              input-debounce="500"
              @filter="filterOptions"
              dense
              filled
              class="search-input"
              bg-color="white"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    无匹配内容
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
            <q-btn
              type="submit"
              label="添加并分析"
              color="primary"
              class="search-btn"
              icon="add_circle"
            />
          </q-form>
        </q-card-section>
      </q-card>
    </div>

    <!-- 告警业务标签区域 -->
    <div v-if="queries.length" class="alert-section q-mt-md">
      <q-card flat bordered>
        <q-card-section>
          <div class="text-h6 text-weight-bold q-mb-md">
            <q-icon name="error_outline" size="sm" class="q-mr-sm"/>
            告警业务
          </div>
          <div class="alert-chips">
            <q-chip
              v-for="(query, index) in queries"
              :key="index"
              removable
              @remove="removeQuery(index)"
              class="alert-chip"
              color="negative"
              text-color="white"
            >
              {{ query }}
            </q-chip>
          </div>
        </q-card-section>
      </q-card>
    </div>

    <!-- 诊断结果区域 -->
    <div v-if="result" class="result-section q-mt-md">
      <q-card flat bordered>
        <q-card-section>
          <div class="text-h6 text-weight-bold">
            <q-icon name="assessment" size="sm" class="q-mr-sm"/>
            预警光缆诊断结果
          </div>
          <p class="text-grey-8">{{ result }}</p>
        </q-card-section>
      </q-card>

      <q-card flat bordered class="q-mt-md">
        <q-card-section>
          <div class="text-h6 text-weight-bold">
            <q-icon name="insights" size="sm" class="q-mr-sm"/>
            当前诊断结果
          </div>
          <pre class="diagnosis-result">{{ formattedJson }}</pre>

          <!-- 添加跳转按钮 -->
          <div class="text-right q-mt-md">
            <q-btn
              color="warning"
              icon="map"
              label="进入地图预警"
              @click="goToGasMap"
              class="action-btn q-mr-md"
            />
            <q-btn
              color="primary"
              icon="arrow_forward"
              label="进入影响范围预警"
              @click="goToFaultPrediction"
              class="action-btn"
            />
          </div>
        </q-card-section>
      </q-card>
    </div>
  </q-page>
</template>

<script>
import axios from 'axios';
import { Dialog,Loading  } from 'quasar';
export default {
  name: 'EsAnaCon',
  data() {
    return {
      formattedJson: [
        { "所属光缆": "光缆1", "数量": 10 },
        { "所属光缆": "光缆2", "数量": 15 }
      ],
      filteredOptions: [],  // 过滤后的选项
      ywNames:'',
      queryInput: '',
      queries: [],
      result: ''
    };
  },
  methods: {
    goToGasMap() {
      // 保存当前分析结果到 localStorage
      this.$router.push('/gis');
    },
    filterOptions(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptions = this.ywNames.filter(v => v.match(filter))
        } else {
          this.filteredOptions = this.ywNames
        }
      });
    },
    addQuery() {
      if (this.queryInput) {
        this.queries.push(this.queryInput);
        this.queryInput = '';
        // this.search();
      }
    },
    removeQuery(index) {
      this.queries.splice(index, 1);

      // 检查 this.queries 是否为空
      if (this.queries.length === 0) {
        localStorage.setItem('queryResult', '[]');
      } else {
        this.search();  // 如果不为空，执行搜索
      }
    },
    async search_bak() {
      try {
        // 发送 GET 请求并等待响应
        const response = await axios.get('http://www.knowoptic.com:4444/get_xiangtongyongtu_names', {
          params: { items_yw: JSON.stringify(this.queries) }
        });

        const responseData = response.data;

        // 提取"所属光缆"字段的值
        const extractedCables = responseData.map(item => item['所属光缆段']);

        console.log('extractedCables',extractedCables);
        // 从 LocalStorage 获取 queryResult
        const storedQueryResult = JSON.parse(localStorage.getItem('queryResult')) || [];
        console.log('storedQueryResult',storedQueryResult)
        // 检查新数组与 LocalStorage 的对比
        const allCablesContained = extractedCables.every(cable => storedQueryResult.includes(cable));

        console.log("all",allCablesContained);
        if (allCablesContained || storedQueryResult.length === 0) {
          // 更新 LocalStorage
          localStorage.setItem('queryResult', JSON.stringify(extractedCables));
        } else {
          // 输出错误信息并移除最后一个输入
          this.showAlert('经过分析当前务无法关联到相同的光缆段，请重新输入其他报错业务；');
          this.queries.pop();  // 移除最后一个输入
          this.result = '经过分析当前业务无法关联到相同的光缆段，请重新输入其他报错业务；';
          return; // 退出方法
        }
        console.log("所属光缆",responseData)

        // 处理成功情况
        const processedData = responseData.map(item => ({
          "所属光缆段": item['所属光缆段'],
          "故障分析值": item['数量'],
          "所属光缆": item['光缆-光路-业务'][0]['所属光缆'],
        }));
        processedData.sort((a, b) => b.故障分析值 - a.故障分析值);
        this.formattedJson = processedData

        // 将处理后的数据数组转换为JSON字符串并展示
        this.result = `当前诊断结果: ${JSON.stringify(processedData)}`;
        localStorage.setItem('渲染', JSON.stringify(responseData));
        localStorage.setItem('链路', JSON.stringify(processedData));

        return ;
      } catch (error) {
        // 处理错误情况
        console.error('Error fetching data:', error);
        this.result = '查询失败';
      }
    },
    async search() {
      Loading.show();
      try {
        // 发送 GET 请求并等待响应
        const response = await axios.get('http://www.knowoptic.com:4444/get_xiangtongyongtu_names', {
          params: { items_yw: JSON.stringify(this.queries) }
        });

        const responseData = response.data;

        // 提取"所属光缆"字段的值
        const extractedCables = responseData.map(item => item['所属光缆段']);

        console.log('extractedCables',extractedCables);
        // 从 LocalStorage 获取 queryResult
        const storedQueryResult = JSON.parse(localStorage.getItem('queryResult')) || [];
        console.log('storedQueryResult',storedQueryResult)
        // 检查新数组与 LocalStorage 的对比
        const allCablesContained = extractedCables.every(cable => storedQueryResult.includes(cable));

        console.log("all",allCablesContained);
        if (allCablesContained || storedQueryResult.length === 0) {
          // 更新 LocalStorage
          localStorage.setItem('queryResult', JSON.stringify(extractedCables));
        } else {
          // 输出错误信息并移除最后一个输入
          this.showAlert('经过分析当前业务无法关联到相同的光缆段，请重新输入其他报错业务；');
          this.queries.pop();  // 移除最后一个输入
          this.result = '经过分析当前业务无法关联到相同的光缆段，请重新输入其他报错业务；';
          return; // 退出方法
        }
        console.log("所属光缆",responseData)

        // 处理成功情况
        const processedData = responseData.map(item => ({
          "所属光缆段": item['所属光缆段'],
          "故障分析值": item['数量'],
          "所属光缆": item['光缆-光路-业务'][0]['所属光缆'],
        }));
        processedData.sort((a, b) => b.故障分析值 - a.故障分析值);
        this.formattedJson = processedData

        // 将处理后的数据数组转换为JSON字符串并展示
        this.result = `当前诊断结果: ${JSON.stringify(processedData)}`;
        localStorage.setItem('渲染', JSON.stringify(responseData));
        localStorage.setItem('链路', JSON.stringify(processedData));

        // 保存当前查询状态
        localStorage.setItem('previousQueries', JSON.stringify(this.queries));
        localStorage.setItem('previousResult', JSON.stringify(this.result));
        localStorage.setItem('previousFormattedJson', JSON.stringify(this.formattedJson));

      } catch (error) {
        // 处理错误情况
        console.error('Error fetching data:', error);
        this.result = '查询失败';
      } finally {
        Loading.hide();
      }
    },
    showAlert(message) {
      this.$q.dialog({
        title: '告警',
        message: message,
        ok: true,
        cancel: false,
      }).onOk(() => {
        // 确认后可以执行的操作
        console.log('用户已确认');
      });
    },
    async addQueryAndSearch() {
      if (this.queryInput) {
        this.queries.push(this.queryInput);
        this.queryInput = '';
        await this.search(); // 直接调用搜索
      }
    },
    // 添加跳转方法
    goToFaultPrediction() {
      // 保存当前分析结果到 localStorage
      localStorage.setItem('链路', JSON.stringify(this.formattedJson));

      // 使用路由导航到故障范围预测页面
      this.$router.push('/FaultResultQuery');
    },
    goToGasMap() {
      // 保存当前分析结果到 localStorage
      console.log("进入地图")
      console.log(this.formattedJson)
      // 找到故障分析值最大的记录
      const maxItem = this.formattedJson.reduce((max, current) => {
        return current["故障分析值"] > max["故障分析值"] ? current : max;
      }, this.formattedJson[0]);

      console.log("maxItem",maxItem)
      console.log("formattedJson",this.formattedJson)

      // 只保留最大值的记录
      this.formattedJson = [maxItem];
      const jsonStr = this.formattedJson[0]['所属光缆段'];
      const matches = jsonStr.match(/\((.*?)\)/);
      const extractedStr = matches ? matches[1] : jsonStr;
      console.log(extractedStr)
      console.log("111111111")
      console.log(this.formattedJson[0]['所属光缆段'])
      let retjson = [{"所属光缆":extractedStr}]
      console.log(retjson)
      localStorage.setItem('alertInfo', extractedStr);

      // 使用路由导航到故障范围预测页面
      this.$router.push('/gas');
    }
  },
  mounted() {
    // 移除清空操作
    localStorage.setItem('queryResult','[]')

    Loading.show();
    // 从 localStorage 获取之前的查询结果
    try {
      const previousQueries = JSON.parse(localStorage.getItem('previousQueries') || '[]');
      const previousResult = JSON.parse(localStorage.getItem('previousResult') || '');
      const previousFormattedJson = JSON.parse(localStorage.getItem('previousFormattedJson') || '[]');

      // 恢复之前的查询状态
      if (previousQueries.length > 0) {
        this.queries = previousQueries;
        this.result = previousResult;
        this.formattedJson = previousFormattedJson;
      }
    } catch (error) {
      console.error('恢复之前查询状态失败:', error);
    }

    // 获取业务名称数据
    axios.get('http://www.knowoptic.com:4444/get_yw_names')
      .then(response => {
        try {
          const data = response.data;
          this.ywNames = data.yw_names;
        } catch (e) {
          console.error('解析 JSON 数据时发生错误:', e);
        }
        console.log('业务名称:', this.ywNames);
      })
      .catch(error => {
        console.error('请求业务名称时发生错误:', error);
      })
      .finally(() => {
        Loading.hide();
      });
  },
};
</script>
<style scoped>
.analysis-container {
  max-width: 1400px;
  margin: 0 auto;
  background: white;
  min-height: 100vh;
}

.search-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.search-card {
  background: white;
}

.search-form {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.search-input {
  flex: 1;
  max-width: 500px;
}

.search-btn {
  margin-top: 4px;
  min-width: 120px;
  border-radius: 8px;
}

.alert-section, .result-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.alert-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.alert-chip {
  transition: all 0.3s ease;
}

.alert-chip:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.diagnosis-result {
  background-color: white;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
  color: #495057;
}

/* 响应式布局 */
@media (max-width: 600px) {
  .search-form {
    flex-direction: column;
  }

  .search-input {
    max-width: 100%;
  }

  .search-btn {
    width: 100%;
    margin-top: 16px;
  }
}

.action-btn {
  min-width: 180px;
  border-radius: 8px;
  font-weight: 500;
  text-transform: none;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateX(5px);
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
</style>
